package jbrowser.session;

import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import jbrowser.api.ClassLoadingException;

public class JarSession implements Session {

    private URL jarFileURL;
    private URLClassLoader classLoader;

    public JarSession(URI uri) throws IOException {
        JarURLConnection jarURLConnection = (JarURLConnection) uri.toURL().openConnection();
        jarFileURL = jarURLConnection.getJarFileURL();
        classLoader = new URLClassLoader(new URL[]{jarFileURL});
    }

    @Override
    public String getHost() {
        return jarFileURL.toString();
    }

    @Override
    public Class loadClass(URI uri) throws ClassLoadingException {
        try {
            JarURLConnection jarURLConnection = (JarURLConnection) uri.toURL().openConnection();
            String className = jarURLConnection.getEntryName().replace("/", ".").replace(".class", "");
            return Class.forName(className, true, classLoader);
        } catch (Exception ex) {
            throw new ClassLoadingException(ex);
        }
    }
}
